package com.armani.controller;

import com.armani.model.ItemModel;
import com.armani.model.Result;
import com.armani.model.SpuModel;
import com.armani.service.ItemService;
import com.armani.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: armani
 * @Package: com.armani.controller
 * @ClassName: ItemController
 * @Description: 商品详情
 * @Author: lenovo
 * @Date: 2021/12/3 0:30
 * @Version: 1.0
 **/
@Controller
@RequestMapping(value = "/item/", produces = "text/html;charset=UTF-8")
public class ItemController {

    @Autowired
    ItemService itemService;

    /**
     * 查询商品详情列表
     *
     * @param name       商品名称
     * @param type
     * @param page
     * @param limit
     * @return 商品详情列表集合
     */
    @RequestMapping(value = "list.do")
    @ResponseBody
    public String itemList(@RequestParam(required = false) String name,
                           @RequestParam(required = false) Integer type,
                           @RequestParam(required = false) Integer page,
                           @RequestParam(required = false) Integer limit) {
        //参数列表
        Map<String, Object> params = new HashMap<>();
        params.put("name", name);
        params.put("type", type);
        if (page != null && limit != null) {
            params.put("offset", (page - 1) * limit);
            params.put("limit", limit);
        }
        List<ItemModel> itemList = itemService.itemList(params);
        Integer count = itemService.count(params);
        Result result = new Result(0, "查询成功", itemList, count);
        return JsonUtil.stringify(result);
    }

    /**
     * 商品添加
     * @param itemModel 添加的参数体
     * @return 添加状态，JSON格式
     */
    @RequestMapping(value = "add.do")
    @ResponseBody
    @Transactional
    public String itemAdd(@RequestBody ItemModel itemModel) {
        itemModel.setCreateTime(new Date());
        itemModel.setLastTime(new Date());
        Integer row=itemService.itemAdd(itemModel);
        Result result=new Result();
        if (row!=null){
            result.setCode(0);
            result.setMsg("添加成功");
        }else {
            result.setCode(1000);
            result.setMsg("添加失败");
        }
        return JsonUtil.stringify(result);
    }
}
